package com.woniuxy.portal.controller;

import cn.hutool.core.util.RandomUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.common.RedisConst;
import com.woniuxy.portal.common.enumeration.Assert;
import com.woniuxy.portal.common.enumeration.BusinessCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yellow Docter
 * @date 2024-10-23
 * @desc 蜗牛创想：www.woniuxy.com
 */
@RestController
@RequestMapping("/email")
@Api(tags = "邮件服务")
public class EmailController {

    /**
     * 模板类
     *      springboot 中自动装配 封装好了的 操作 指定 中间件的模板
     *
     *   springboot 操作jdbc的模板类 JdbcTemplate
     *   springboot 操作Redis的模板类 RedisTemplate   (stringRedisTemplate 操作字符串的模板类型)
     *   springboot 操作Rabbit的模板类 RabbitTemplate
     *   springboot 操作xxx的模板类 XXXTemplate
     */

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${spring.mail.username}")
    private String from;

    @GetMapping("/send")
    @ApiOperation("发送邮件")
    public ResponseEntity<String> sendEmail(String address) {

        //生成验证码
        String code = RandomUtil.randomNumbers(4);

        //MQ(模板类) 发送邮件    到MQ 系统中
        String text = "蜗牛书城用于注册，验证码是:" + code;
        Map<String,String> map = new HashMap<>();
        map.put("subject","蜗牛书城");
        map.put("text",text);
        map.put("from",from);
        map.put("to",address);

        //springmvc 中自带的 json 转换工具
//        ObjectMapper objectMapper = new ObjectMapper();
//        String json = objectMapper.writeValueAsString(map);

        //参数1： 队列   参数2：数据
        rabbitTemplate.convertAndSend("email.queue", map);
        //              监听MQ  获取消息 (发送邮件)

        //验证存储在redis中
        String key = RedisConst.EMAIL_ADDRESS_PREFIX + ":" + address;
        stringRedisTemplate.opsForValue().set(
                key,
                code,
                5,
                TimeUnit.MINUTES);
        return ResponseEntity.ok("发送消息成功...");
    }


}
